package com.tanhua.api.mongdb;

import cn.hutool.core.collection.CollectionUtil;
import com.tanhua.domain.mogo.*;
import com.tanhua.domain.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.List;

@Service
public class PublishApiImpl implements PublishApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;

    public String save(Publish publish) {

        //1 保存数据到动态发布表
        publish.setCreated(System.currentTimeMillis());
        publish.setId(new ObjectId()); //自己设置主键id
        //给大数据提供的一个属性赋值
        publish.setPid(idService.getNextId("quanzi_publish")); //数值类型的唯一值
        mongoTemplate.insert(publish,"quanzi_publish");
        //2 保存数据到个人动态表
        Album album = new Album();
        album.setPublishId(publish.getId());
        album.setCreated(publish.getCreated());
        mongoTemplate.insert(album,"quanzi_album_"+publish.getUserId());
        //3 查询发布者（登录者）的好友信息
        Query query = new Query(Criteria.where("userId").is(publish.getUserId()));
        List<Friend> friendsList = mongoTemplate.find(query, Friend.class);
        //4 给对应好友时间线表保存数据
        if(CollectionUtil.isNotEmpty(friendsList)){
            for (Friend friend : friendsList) {
                TimeLine timeLine = new TimeLine();
                timeLine.setCreated(publish.getCreated());
                timeLine.setPublishId(publish.getId());
                timeLine.setUserId(publish.getUserId());
                mongoTemplate.insert(timeLine,"quanzi_time_line_"+friend.getFriendId());
            }
        }

        return publish.getId().toString();
    }

    @Override
    public PageBeanVo findAlbumByPage(Integer page, Integer pagesize, Long userId) {

        //1 先查询登录者的个人动态表获取到publishId
        Query query = new Query();
        query.with(new Sort(Sort.Direction.DESC,"created"));
        query.skip((page-1)*pagesize).limit(pagesize);
        List<Album> list = mongoTemplate.find(query, Album.class, "quanzi_album_" + userId);
        long count = mongoTemplate.count(query, "quanzi_album_" + userId);

        //2根据publishId获取到动态详情数据
        List<Publish> publishList=new ArrayList<>();
        if(CollectionUtil.isNotEmpty(list)){
            for (Album album : list) {
                Publish publish = mongoTemplate.findById(album.getPublishId(), Publish.class);
                publishList.add(publish);
            }
        }
        //组装分页
        PageBeanVo pageBeanVo = new PageBeanVo(page,pagesize,count,publishList);

        // 返回分页
        return pageBeanVo;
    }

    @Override
    public PageBeanVo findTimeLineByPage(Integer page, Integer pagesize, Long userId) {

        //1 先查询登录者的时间线表获取到publishId
        Query query = new Query();
        query.with(new Sort(Sort.Direction.DESC,"created"));
        query.skip((page-1)*pagesize).limit(pagesize);
        List<TimeLine> list = mongoTemplate.find(query, TimeLine.class, "quanzi_time_line_" + userId);
        long count = mongoTemplate.count(query, "quanzi_time_line_" + userId);

        //2根据publishId获取到动态详情数据publish
        List<Publish> publishList=new ArrayList<>();
        if(CollectionUtil.isNotEmpty(list)){
            for (TimeLine timeLine : list) {
                Publish publish = mongoTemplate.findById(timeLine.getPublishId(), Publish.class);
                if(publish.getState()==1){
                        //审核通过的publish动态数据
                    publishList.add(publish);
                }
            }
        }

        //组装分页
        PageBeanVo pageBeanVo = new PageBeanVo(page,pagesize,count,publishList);
        // 返回分页
        return pageBeanVo;
    }

    @Override
    public PageBeanVo findRecommendByPage(Integer page, Integer pagesize, Long userId) {

        //1 先查询登录者的推荐表根据登录用户的id获取到publishId
        Query query = new Query(Criteria.where("userId").is(userId));
        query.with(new Sort(Sort.Direction.DESC,"created"));
        query.skip((page-1)*pagesize).limit(pagesize);
        List<RecommendQuanzi> list = mongoTemplate.find(query, RecommendQuanzi.class, "recommend_quanzi");
        long count = mongoTemplate.count(query, "recommend_quanzi");

        //2根据publishId获取到动态详情数据publish
        List<Publish> publishList=new ArrayList<>();
        if(CollectionUtil.isNotEmpty(list)){
            for (RecommendQuanzi recommendQuanzi : list) {
                Publish publish = mongoTemplate.findById(recommendQuanzi.getPublishId(), Publish.class);
                if(publish.getState()==1){
                    //审核通过的publish动态数据
                    publishList.add(publish);
                }
            }
        }
        //组装分页
        PageBeanVo pageBeanVo = new PageBeanVo(page,pagesize,count,publishList);
        // 返回分页
        return pageBeanVo;
    }

    @Override
    public Publish findById(String publishId) {
        Publish publish = mongoTemplate.findById(new ObjectId(publishId), Publish.class);
        return publish;
    }

    @Override
    public PageBeanVo findUserPublish(Integer page, Integer pagesize, Long uid, Integer state) {

        Query query = new Query();

        Criteria criteria = new Criteria();
        if(uid!=null){
            criteria.and("userId").is(uid);
        }
        if(state!=null){
            criteria.and("state").is(state);
        }
        query.addCriteria(criteria);

        query.with(new Sort(Sort.Direction.DESC,"created"));
        query.skip((page-1)*pagesize).limit(pagesize);
        List<Publish> publishList = mongoTemplate.find(query, Publish.class);
        long count = mongoTemplate.count(query, Publish.class);
        return new PageBeanVo(page,pagesize,count,publishList);
    }

    @Override
    public void updateState(String publishId, Integer state) {

        Query query = new Query(Criteria.where("id").is(new ObjectId(publishId)));
        Update update = new Update();
        update.set("state",state);
        mongoTemplate.upsert(query,update,Publish.class);
    }

    @Override
    public Publish findByPid(Long pid) {

        Query query = new Query(Criteria.where("pid").is(pid));
        return mongoTemplate.findOne(query,Publish.class);
    }
}
